/**
 * @Description: 监控箱报警统计
 * @Author: WYX.
 * @Date: 2018/5/3 13:37.
 */
var talkMainDT;
var dealMainDT;
var orgSelect = "";
var orgTableSelect = "";
var date = new Date;
$("#alarmPushTime").val(date.getFullYear());
/*曲线图表*/
var barChartOptions = {
    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
    scaleBeginAtZero: true,
    //Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines: true,
    //String - Colour of the grid lines
    scaleGridLineColor: "rgba(0,0,0,.05)",
    //Number - Width of the grid lines
    scaleGridLineWidth: 1,
    //Boolean - Whether to show horizontal lines (except X axis)
    scaleShowHorizontalLines: true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    //Boolean - If there is a stroke on each bar
    barShowStroke: true,
    //Number - Pixel width of the bar stroke
    barStrokeWidth: 2,
    //Number - Spacing between each of the X value sets
    barValueSpacing: 5,
    //Number - Spacing between data sets within X values
    barDatasetSpacing: 1,
    //关闭提示
    showTooltips: false,
    //String - A legend template
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
    //Boolean - whether to make the chart responsive
    responsive: true,
    maintainAspectRatio: true,
    onAnimationComplete: function () {
        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y);
            });
        });
    }
};
barChartOptions.datasetFill = false;

//Date picker
$('#alarmPushTime').datepicker({
    language: "zh-CN",
    format: 'yyyy',
    autoclose: true,
    startView: 'years',
    maxViewMode: 'years',
    minViewMode: 'years',
}).on('hide', function (e) {
    $.getAlarmCounts();
});

//标志分类统计柱状图
var alarmPushType, startTime, orgIds, deviceId, endTime;
$.getAlarmCounts = function () {
    alarmPushType = 8;
    var time = $("#alarmPushTime").val();
    if (time) {
        startTime = new Date(time).getTime() / 1000;
        endTime = startTime - 0 + 31536000;
    } else {
        startTime = null
        endTime = null
    }

    deviceId = $("#deviceId").val();
    $.ajax({
        url: '../rds_monitorAlarm/getMonthCount',
        type: 'post',
        data: {
            alarmPushType: alarmPushType,
            startTime: startTime,
            endTime: endTime,
            orgIds: orgIds,
            deviceId: deviceId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var signCounts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                    var counts = msg.jsonData;
                    var allCount = 0;
                    counts.forEach(function (item) {
                        if (item.month) {
                            var index;
                            index = item.month.substr(4) - 1;
                            signCounts[index] = item.count;
                            allCount += item.count;
                        }
                    })
                    $("#word").html("报警统计图(" + allCount + ")");
                    $("#barChart").remove();
                    $("#barChartParent").html("<canvas id='barChart' style='height:230px'></canvas>");
                    var areaChartData = {
                        labels: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                        datasets: [
                            {
                                label: "Electronics",
                                fillColor: "#00c0ef",
                                strokeColor: "#00c0ef",
                                pointColor: "rgba(210, 214, 222, 1)",
                                pointStrokeColor: "#c1c7d1",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: signCounts
                            }
                        ]
                    };
                    var barChartCanvas = $("#barChart").get(0).getContext("2d");
                    var barChart = new Chart(barChartCanvas);
                    var barChartData = areaChartData;
                    barChart.Bar(barChartData, barChartOptions);
                }
            }
        }
    });
};

var allOrgList = "", gOrgOptionList = "";
//按维护单位查询的下拉框
$.getDealOrg = function () {
    $.ajax({
        url: '../rds_count/getDealOrg',
        type: 'post',
        async: false,
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var orgList = msg.jsonData;
                    var $orgSelect = $("#orgIds");
                    $("#orgIdBlock").show();
                    orgList.forEach(function (item) {
                        allOrgList += "," + item.orgId;
                        gOrgOptionList += "<option value='" + item.orgId + "'>" + item.orgName + "</option>";
                        $orgSelect.append("<option value='" + item.orgId + "'>" + item.orgName + "</option>")
                    })
                    orgIds = (allOrgList = allOrgList.substr(1));
                    alarmHistoryOrgIds = orgIds
                }
            }
        }
    })
};

$("#yearBtn").click(function () {
    $("#alarmPushTime").val("")
    $.getAlarmCounts()
})

$("#orgIds").change(function () {
    if ($(this).val() == -1)
        orgIds = allOrgList
    else
        orgIds = $(this).val()
    $.getAlarmCounts()

})

var alarmHistoryDt = null;
var alarmHistorySubTime = "",
    alarmHistoryOrgIds = "",
    alarmHistoryDeviceId;
$(function () {
    $.getDealOrg();
    $.getAlarmCounts();
    alarmHistoryDt = $("#alarmHistoryDataTable").DataTable({
        ajax: {
            url: "../rds_monitorAlarm/showAlarmHistory",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.deviceType = 8;
                d.orgIds = alarmHistoryOrgIds;
                d.time = alarmHistorySubTime;
                d.deviceId = alarmHistoryDeviceId;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "alarmPushContent"
        }, {
            data: "orgName"
        }, {
            data: "alarmPushTime",
            render: function (data) {
                return formatDateTime(data)
            }
        }, {
            data: "alarmDeviceId"
        }],
        dom: "<'row'<'col-md-2'l><'#alarmHistoryTool.col-md-10'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            $("#alarmHistoryTool").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat' " +
                "onclick='alarmHistoryDt.ajax.reload(null, false);' ><i class='fa fa-cog'></i>刷新</button></div> " +
                "<div class='input-group-sm' style='display:inline-block'>";

            if (gUserLoginResult.orgType != 0) {
                strToolBar += $.getOrgSelectHtml();
            }
            strToolBar += " <input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='设备码'> " +
                "<input type='text' class='form-control' id='alarmHistoryDatePicker' placeholder='操作时间' readonly> " +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchAlarmHistory()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            $("#alarmHistoryTool").append(strToolBar);
            $("#alarmHistoryDatePicker").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).searchAlarmHistory();
                }
            });
            $("#alarmHistoryDatePicker").focus(function () {
                $('#alarmHistoryDatePicker').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        applyLabel: '确认',
                        cancelLabel: '取消',
                        fromLabel: '从',
                        toLabel: '到',
                        weekLabel: 'W',
                        customRangeLabel: 'Custom Range',
                        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    }
                }).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                }).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                });
            })
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        destroy: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    var oTable = $('#alarmHistoryDataTable').dataTable();
    if(!(gUserLoginResult.userActors.includes("1")||gUserLoginResult.userActors.includes("7")))
        oTable.fnSetColumnVis(2, false);//隐藏列
    $.selectOrg = function (orgId) {
        alarmHistoryOrgIds = orgId;
        if (!orgId.includes(","))
            oTable.fnSetColumnVis(2, false);//隐藏列
        else
            oTable.fnSetColumnVis(2, true);//隐藏列

    }
});

$.getOrgSelectHtml = function () {
    var html = "<select id='orgList' class='form-control' onchange='$.selectOrg(this.value)'>" +
        "<option value='" + allOrgList + "'>所有公司</option>" + gOrgOptionList + "</select>";

    return html
}

$.fn.searchAlarmHistory = function () {
    alarmHistorySubTime = $("#alarmHistoryDatePicker").val()
    alarmHistoryDeviceId=$("#searchText").val()
    alarmHistoryDt.search(null).draw();
}


// 搜索框查询操作
$.fn.searchDT = function () {
    var searchText = $("input[name='searchText']").val();
    if (searchText == "") {
        searchText = -1;
    }
    var orgTableName = $("#orgTableChoose").val();
    var searchContext = searchText + "#" + orgTableName;
    dealMainDT.search(searchContext).draw();
    talkMainDT.search(searchContext).draw();
};

$.selectAlarmPushType = function (e) {
    alarmHistoryDeviceType = e;
}
//使时间插件使用正常
$.dateReturn = function () {
    $(".dropdown-menu").css("min-width", "100%");
};


$.refreshDatables = function () {
    talkMainDT.ajax.reload(null, false);
    dealMainDT.ajax.reload(null, false);
};


//Date picker
$('#datepicker').datepicker({
    language: "zh-CN",
    format: 'yyyy',
    autoclose: true,
    startView: 'years',
    maxViewMode: 'years',
    minViewMode: 'years',
}).on('hide', function (e) {
    year = $("#datepicker").val();
    $.getlineChart();
});
//设置默认时间
$('#datepicker').datepicker('setDate', new Date());
$('#datepicker').datepicker('setEndDate', '2100');
$('#datepicker').datepicker('setStartDate', '2000');


